package Services

import (
	"errors"
	"gorm.io/gorm"
	"minititok/Entities"
	"minititok/databases"
)

func EnsureLikes(username string, Av string) (*Entities.Like, error) {
	var likes Entities.Like
	DBerr := databases.DB.Where("username = ? AND av = ?", username, Av).First(&likes).Error
	if errors.Is(DBerr, gorm.ErrRecordNotFound) {
		// 创建一条默认 liked = false 的记录
		newLike := Entities.Like{
			Username: username,
			Av:       Av,
			Liked:    false,
		}
		if err := databases.DB.Create(&newLike).Error; err != nil {
			return nil, err
		}
		return &newLike, nil
	} else if DBerr != nil {
		return nil, DBerr
	}
	return &likes, nil
}

func FindLikesByAvAndUsername(username string, Av string) (*Entities.Like, error) {
	var likes Entities.Like
	err := databases.DB.Where("username = ? AND av = ?", username, Av).First(&likes).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, err
	}
	return &likes, err
}

func UpdataLikes(likes *Entities.Like, liked bool) error {
	err := databases.DB.Model(likes).
		//Select("liked").
		//Where("av = ? AND username = ?", likes.Av, likes.Username).
		Update("liked", liked).
		Error
	if err != nil {
		return err
	}
	return nil
}
